package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        List<Category> categoryList = categoryMapper.findAll();

        return categoryList;
    }

    /*由于菜品分类的编辑修改代码是采用的直接从浏览器回填,并没有从后端查询回显到前端前端,导致category属性:更新时间 更新人为null
    又由于同时使用mybatis mybatisplus技术 (mybatis会先生成sql语句,生成的sql语句不会对这四个属性进行处理(动态sql对于null值的处理))
    从而MyMetaObjectHandler对更新人 更新时间 的代码失效

    解决方法:  不同时使用mybatis和mybatisplus技术
    */
    @Override
    public void add(Category category) {
//        category.setId(IdUtil.getSnowflake(1, 1).nextId());
//        category.setCreateUser(1L);
//        category.setCreateTime(new Date());
//        category.setUpdateUser(1L);
//        category.setUpdateTime(new Date());
        categoryMapper.insert(category);
    }

    @Override
    public void update(Category category) {
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        categoryMapper.updateById(category);
    }

    @Override
    public ResultInfo deleteById(Long id) {
        Integer countDish = categoryMapper.countDishByCategory(id);
        if(countDish > 0){
            throw new CustomException("该菜品分类下存在商品，删除失败！");
        }
        Integer countSetmeal = categoryMapper.countSetmealByCategory(id);
        if(countSetmeal > 0){
            throw new CustomException("该套餐分类下存在商品，删除失败！");
        }
        //if (countDish == 0 && countSetmeal == 0) {
            categoryMapper.deleteById(id);
            return ResultInfo.success(null);
        //}
        //return ResultInfo.error("此分类下存在商品,删除失败!");
    }

    //回显菜品分类
    @Override
    public List<Category> findByType(Integer type) {
        //select * from category where type = #{}
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getType,type);
        List<Category> categoryList =  categoryMapper.selectList(categoryLambdaQueryWrapper);
        return categoryList;
    }
}
